package com.zhkj.lib.base

import androidx.lifecycle.ViewModelProvider
import com.zhkj.lib.http.HttpResponseStatus

abstract class ViewModelFragment<ViewModel : BaseViewModel> : BaseFragment() {

    protected lateinit var viewModel: ViewModel

    override fun doBeforeInitUI() {
        viewModel = setViewModel()
        initViewModel()
    }

    /**
     * 生成ViewModel
     */
    abstract fun setViewModel(): ViewModel

    /**
     * 初始化ViewModel
     */
    open fun initViewModel() {
    }

    /**
     * 显示加载框(客户要求去掉)
     */
    fun handlerResponseStatus(status: HttpResponseStatus.Status, errorTip: String, showLoading: Boolean = false) {
        when (status) {
            HttpResponseStatus.Status.START -> if (showLoading) showLoadingView()
            HttpResponseStatus.Status.SUCCESS -> if (showLoading) hideLoadingView()
            HttpResponseStatus.Status.FAILURE -> {
                if (showLoading) hideLoadingView()
                toast(errorTip)
            }
        }
    }

    /**
     * 生成ViewModel的方法
     */
    inline fun <reified VM : BaseViewModel> createViewModel(share2Activity: Boolean): VM {
        val factory = ViewModelProvider.AndroidViewModelFactory(BaseApplication.INSTANCE)
        return if (share2Activity) ViewModelProvider(requireActivity(), factory).get(VM::class.java)
        else ViewModelProvider(this, factory).get(VM::class.java)
    }
}